package com.iqiyi.pps.epg.web.timer;

import com.iqiyi.pps.epg.core.model.push.AutoPushMsg;
import com.iqiyi.pps.epg.core.service.push.AutoPushMsgService;
import com.iqiyi.pps.epg.web.thread.AutoPushToDevicesThread;
import com.iqiyi.pps.epg.web.thread.SetAutoPushStatusThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by zhang on 2016/2/23.
 */
@Deprecated
public class AutoPushMsgTrigger {
    private static Logger logger = LoggerFactory.getLogger(AutoPushMsgTrigger.class);

    private static final int NTHREADES = 10;
    @Autowired
    private AutoPushMsgService autoPushMsgService;

    public void task() {
        logger.info("[AutoPushMsgTrigger][start]");
        try {
            // 获取当前时间
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.SECOND, 59);
            Long endTime = calendar.getTimeInMillis();
            Long maxTime = calendar.getTimeInMillis();
            calendar.add(Calendar.DATE, -1);
            Long startTime = calendar.getTimeInMillis();
            int start = 0;
            int max = 100;
            // 分页获取100个推送任务，并分配给线程推送，同时根据id更新推送中状态
            long pushCount = 0;
            ExecutorService exec = Executors.newFixedThreadPool(NTHREADES);
            while(true) {
                List<AutoPushMsg> autoPushMsgs = autoPushMsgService.getPushMsg(startTime, endTime, start, max);
                if (autoPushMsgs == null || autoPushMsgs.size() <= 0) {
                    break;
                }

                StringBuffer ids = new StringBuffer();
                for (AutoPushMsg autoPushMsg : autoPushMsgs) {
                    ids.append(autoPushMsg.getId()).append(",");
                }

                autoPushMsgService.updatePushStatusByIds(ids.toString(), AutoPushMsg.AUTO_PUSH_STATUS_PUSHING);

                exec.execute(new AutoPushToDevicesThread(autoPushMsgs));

                pushCount = pushCount + autoPushMsgs.size();
                if (autoPushMsgs.size() < max) {
                    break;
                }
                start = start + max;
            }
            logger.info("[AutoPushMsgTrigger][Pushing][pushCount={}]", pushCount);
            // 更新剩余推送任务状态为播控下线
            Thread setAutoPushStatusThread = new Thread(new SetAutoPushStatusThread(startTime, endTime));
            setAutoPushStatusThread.start();
        } catch(Exception e) {
            logger.error("[AutoPushMsgTrigger][error]", e);
        } finally {
            logger.info("[AutoPushMsgTrigger][end]");
        }
    }
}
